package com.xzh.seckill.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wf.captcha.ArithmeticCaptcha;
import com.xzh.seckill.config.AccessLimit;
import com.xzh.seckill.exception.GlobalException;
import com.xzh.seckill.pojo.Order;
import com.xzh.seckill.pojo.SeckillOrder;
import com.xzh.seckill.pojo.User;
import com.xzh.seckill.rabbitmq.MQSender;
import com.xzh.seckill.service.IGoodsService;
import com.xzh.seckill.service.IOrderService;
import com.xzh.seckill.service.ISeckillOrderService;
import com.xzh.seckill.utils.JsonUtil;
import com.xzh.seckill.vo.GoodsVo;
import com.xzh.seckill.vo.RespBean;
import com.xzh.seckill.vo.RespBeanEnum;
import com.xzh.seckill.vo.SeckillMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Controller
@RequestMapping("/seckill")
public class SeckillController implements InitializingBean {

    @Autowired
    private IGoodsService iGoodsService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MQSender mqSender;
    @Autowired
    private DefaultRedisScript<Long> script;

    private Map<Long,Boolean> EmptyStockMap = new HashMap<>();

    //Windows优化前QPS:310.9
    //Linux优化前QPS:166.3
    //windows优化后QPS:
    @RequestMapping("/doSeckill1")
    public String doSeckill1(Long goodsId,Model model, User user)
    {
        System.out.println(goodsId+" "+user);
        if(user==null)
        {
            return "login";
        }
        model.addAttribute("user",user);
        //System.out.println("goodsID:"+goodsID);
        GoodsVo goods = iGoodsService.findGoodsVoByGoodsId(goodsId);
       // System.out.println("goods==="+goods);
        //判断库存
        if(goods.getStockCount()<=0)
        {
            model.addAttribute("errmsg", RespBeanEnum.EMPTY_STOCK.getMessage());
            return "secKillFail";
        }
        //判断是否重复购买
        SeckillOrder seckillorder = seckillOrderService.getOne(new QueryWrapper<SeckillOrder>().
                eq("user_id", user.getId()).eq("goods_id", goodsId));
        //System.out.println("seckillorder:==="+seckillorder);
        if(seckillorder!=null){
            model.addAttribute("errmsg",RespBeanEnum.REPEATE_ERROR.getMessage());
            return "secKillFail";
        }
        Order order = orderService.seckill(user,goods);
        model.addAttribute("order",order);
        model.addAttribute("goods",goods);
        //System.out.println(user);
        return "orderDetail";
    }

    @RequestMapping(value = "/doSeckillx",method = RequestMethod.POST)
    @ResponseBody
    public RespBean doSeckillx(Long goodsId, Model model, User user)
    {
        if(user==null)
        {
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }

        GoodsVo goods = iGoodsService.findGoodsVoByGoodsId(goodsId);
        //判断库存
        if(goods.getStockCount()<=0)
        {
            model.addAttribute("errmsg", RespBeanEnum.EMPTY_STOCK.getMessage());
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }
        //判断是否重复购买
        /*SeckillOrder seckillorder = seckillOrderService.getOne(new QueryWrapper<SeckillOrder>().
                eq("user_id", user.getId()).eq("goods_id", goodsId));*/
        SeckillOrder seckillorder = (SeckillOrder) redisTemplate.opsForValue().get("order:"+user.getId()+":"+ goodsId);
        if(seckillorder!=null){
            model.addAttribute("errmsg",RespBeanEnum.REPEATE_ERROR.getMessage());
            return RespBean.error(RespBeanEnum.REPEATE_ERROR);
        }
        Order order = orderService.seckill(user,goods);
        return RespBean.success(order);
    }

    @RequestMapping(value = "/{path}/doSeckill",method = RequestMethod.POST)
    @ResponseBody
    public RespBean doSeckill(Long goodsId, User user, @PathVariable String path)
    {
        if(user==null)
        {
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        ValueOperations valueOperations = redisTemplate.opsForValue();
        boolean check = orderService.checkPath(user,goodsId,path);
        if(!check){
            return RespBean.error(RespBeanEnum.REQUEST_ILLEGAL);
        }
        //判断是否重复购买
        SeckillOrder seckillorder = (SeckillOrder) redisTemplate.opsForValue().get("order:"+user.getId()+":"+ goodsId);
        if(seckillorder!=null){
            return RespBean.error(RespBeanEnum.REPEATE_ERROR);
        }
        //内存标记，减少redis的访问
        if(EmptyStockMap.get(goodsId)){
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }
        //预减库存
        //Long stock = valueOperations.decrement("seckillGoods" + goodsId);
        Long stock = (Long) redisTemplate.execute(script, Collections.singletonList("seckillGoods" + goodsId),
                Collections.EMPTY_LIST);
        if(stock==0){
            EmptyStockMap.put(goodsId,true);
            //valueOperations.increment("seckillGoods" + goodsId);
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }
        SeckillMessage seckillMessage = new SeckillMessage(user, goodsId);
        mqSender.sendSeckillMessage(JsonUtil.object2JsonStr(seckillMessage));
        return RespBean.success(0);

        /*
        GoodsVo goods = iGoodsService.findGoodsVoByGoodsId(goodsId);
        //判断库存
        if(goods.getStockCount()<=0)
        {
            model.addAttribute("errmsg", RespBeanEnum.EMPTY_STOCK.getMessage());
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }
        //判断是否重复购买
        SeckillOrder seckillorder = seckillOrderService.getOne(new QueryWrapper<SeckillOrder>().
                eq("user_id", user.getId()).eq("goods_id", goodsId));
        //SeckillOrder seckillorder = (SeckillOrder) redisTemplate.opsForValue().get("order:"+user.getId()+":"+ goodsId);
        if(seckillorder!=null){
            model.addAttribute("errmsg",RespBeanEnum.REPEATE_ERROR.getMessage());
            return RespBean.error(RespBeanEnum.REPEATE_ERROR);
        }
        Order order = orderService.seckill(user,goods);
        return RespBean.success(order);
         */
    }

    //获取秒杀地址
    @AccessLimit(second=5,maxCount=5,needLogin=true)
    @RequestMapping(value = "/path",method = RequestMethod.GET)
    @ResponseBody
    public RespBean getpath(User user, Long goodsId, String captcha, HttpServletRequest request)
    {
        if(user==null){
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        //限制访问次数，5秒内访问5次
        /*ValueOperations valueOperations = redisTemplate.opsForValue();
        String uri = request.getRequestURI();
        Integer count = (Integer) valueOperations.get(uri + ":" + user.getId());
        if(count==null){
            valueOperations.set(uri+":"+user.getId(),1,5,TimeUnit.SECONDS);
        }else if(count<5){
            valueOperations.increment(uri+":"+user.getId());
        }else{
            return RespBean.error(RespBeanEnum.ACCESS_LIMIT_REAHCED);
        }*/
        boolean check = orderService.checkCaptcha(user,goodsId,captcha);
        if(!check){
            return RespBean.error(RespBeanEnum.ERROR_CAPTCHA);

        }
        String path = orderService.createPath(user,goodsId);
        return RespBean.success(path);
    }

    @RequestMapping(value = "/captcha",method = RequestMethod.GET)
    public void captcha(User user, Long goodsId, HttpServletResponse response)
    {
        if(user==null||goodsId<0){
            throw new GlobalException(RespBeanEnum.REQUEST_ILLEGAL);
        }
        //设置请求头为输出图片的类型
        response.setContentType("image/jpg");
        response.setHeader("Pargam","No-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires",0);

        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 32, 3);
        redisTemplate.opsForValue().set("captcha:"+user.getId()+":"+goodsId,captcha.text(),300, TimeUnit.SECONDS);
        try {
            captcha.out(response.getOutputStream());
        } catch (IOException e) {
            log.error("验证码生产失败",e.getMessage());
        }
    }

    //系统初始化，把商品数量加载到Redis
    @Override
    public void afterPropertiesSet() throws Exception {
        List<GoodsVo> list = iGoodsService.findGoodsVo();
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        list.forEach(goodsVo -> {
            redisTemplate.opsForValue().set("seckillGoods"+goodsVo.getId(),goodsVo.getStockCount());
            EmptyStockMap.put(goodsVo.getId(),false);
        });
    }

    //获取秒杀结果
    @RequestMapping(value = "/result",method = RequestMethod.GET)
    @ResponseBody
    public RespBean getResult(User user,Long goodsId){
        if(user==null){
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        Long orderId = seckillOrderService.getResult(user,goodsId);
        return RespBean.success(orderId);
    }
}
